from flask import  Flask, render_template,request,escape
import requests
import matplotlib.pyplot as plt
import json

app = Flask(__name__)
def log_request(req:"flask request",res:str):
	with open("vsearch.log","a") as log:
		print(req.form,req.host_url,req.remote_addr,file=log,sep="|")

@app.route('/entry',methods=['post','get'])
def hello_entry():
	user = request.form.get("user")
	log_request(request,user)
	return render_template('entry.html',the_title='计算机视觉')

@app.route("/login",methods=['get'])
def index()-> 'html':
	title ='welcome'
	return render_template("login.html",the_title=title)


@app.route("/remote",methods=["post"])
def remote():
	image_url=request.form['remote']
	endpoint = "https://view-summer.cognitiveservices.azure.com/"
	subscription_key = "a11059e389a44583916a080880f590e6"
	analyze_url = endpoint + "vision/v3.1/analyze"   
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'visualFeatures': 'Categories,Description,Color'}
	data = {'url': image_url}
	response = requests.post(analyze_url, headers=headers,  params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	print(json.dumps(response.json()))
	image_caption = analysis["description"]["captions"][0]["text"].capitalize()
	confidence3 = analysis["description"]["captions"][0]["confidence"]
	return render_template('entry.html',remote=str(image_caption),confidence3=str(confidence3),img_url1=image_url)

	

@app.route("/items",methods=["POST"])
def items():
	image_url=request.form["items"]
	landmark_analyze_url = 'https://view-summer.cognitiveservices.azure.com/' + "vision/v3.1/models/landmarks/analyze"
	subscription_key='a11059e389a44583916a080880f590e6'
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'model': 'landmarks'}
	data = {'url': image_url}
	response = requests.post(
    landmark_analyze_url, headers=headers, params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	assert analysis["result"]["landmarks"] is not []
	print(analysis)
	landmark_name = analysis["result"]["landmarks"][0]["name"].capitalize()
	confidence=analysis["result"]["landmarks"][0]["confidence"]
	return render_template('entry.html', items=str(landmark_name),confidence1=str(confidence),img_url2=image_url)

@app.route("/person",methods=["POST"])
def person():
	image_url=request.form["person"]
	subscription_key = "a11059e389a44583916a080880f590e6"
	assert subscription_key
	vision_base_url = "https://view-summer.cognitiveservices.azure.com/"
	celebrity_analyze_url = vision_base_url + "models/celebrities/analyze"
	headers = {'Ocp-Apim-Subscription-Key': subscription_key}
	params = {'model': 'celebrities'}
	data = {'url': image_url}
	response = requests.post(celebrity_analyze_url, headers=headers, params=params, json=data)
	response.raise_for_status()
	analysis = response.json()
	celebrity_name = analysis["result"]["celebrities"][0]["name"].capitalize()
	confidence2=analysis["result"]["celebrities"][0]["confidence"]
	return render_template('entry.html',person=str(celebrity_name),confidence2=str(confidence2),img_url3=image_url)

@app.route("/viewlog")
def view_log():
	contents=[]
	with open("vsearch.log","r") as log:
		for line in log:
			contents.append([])
			for item in line.split("|"):
				contents[-1].append(escape(item))
		titles= ["Formdata","Host_url","Remote_addr"]
	return render_template('view.html',the_data=contents,the_titles=titles)
	

if __name__ == '__main__':
	app.run(debug= True)